package refobjects

import (
	"fmt"
)

type RefObjectWrapper struct {
	config       string
	objRef       *RefWrapper
	releaseFuncs *SyncFuncList
}

func NewRefObjectWrapper() *RefObjectWrapper {
	return &RefObjectWrapper{releaseFuncs: NewSyncFuncList()}
}

func (this *RefObjectWrapper) releasePre() {

	if this.objRef != nil {
		this.releaseFuncs.ExecuteAndRemoveAll()
		this.objRef.Close()
		this.objRef = nil
	}
}

func (this *RefObjectWrapper) StatusText() string {
	if this.objRef == nil {
		return "NULL"
	}
	obj := this.objRef.Object
	if obj == nil {
		return "Object Null"
	}

	if lvIntf, ok := obj.(StatusQuery); ok {
		return lvIntf.StatusQuery()
	}
	return fmt.Sprintf("%v", obj)
}

func (this *RefObjectWrapper) Close() error {
	this.releasePre()
	return nil
}

func (this *RefObjectWrapper) Object() any {
	if this.objRef == nil {
		return nil
	}
	return this.objRef.Object
}

func (this *RefObjectWrapper) UpdateConfig(s string) (changed bool, err error) {
	if this.config == s {
		return false, nil
	}
	this.releasePre()

	this.config = s
	if len(s) == 0 {
		return true, nil
	}

	objRef, err := Acquire(this.config)
	if err != nil {
		return true, err
	}
	this.objRef = objRef
	return true, nil
}

type StatusQuery interface {
	StatusQuery() string
}
